package com.jyy.prefabricated.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.BatchDto;
import com.jyy.prefabricated.dto.CoursePackageDto;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.entity.CoursePackage;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.entity.TrainingOrganizationStock;
import com.jyy.prefabricated.enums.OrderTypeEnum;
import com.jyy.prefabricated.mapper.StudentCoursePackageMapper;
import com.jyy.prefabricated.mapper.TrainingOrganizationStockMapper;
import com.jyy.prefabricated.service.CoursePackageService;
import com.jyy.prefabricated.service.TrainingOrganizationStockService;
import com.jyy.prefabricated.utils.OrderUtil;
import com.jyy.prefabricated.utils.UserSessionUtil;
import com.jyy.prefabricated.utils.UserUtils;
import com.jyy.prefabricated.vo.CoursePackageData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * 课程包
 *
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class CoursePackageController {

    @Autowired
    private CoursePackageService coursePackageService;
    @Autowired
    private TrainingOrganizationStockService trainingOrganizationStockService;

    @Autowired
    private UserUtils userUtils;

    @Resource
    private StudentCoursePackageMapper studentCoursePackageMapper;

    @Resource
    private TrainingOrganizationStockMapper trainingOrganizationStockMapper;

    /**
     * 新增课程包
     *
     * @param dto
     * @return
     */
    @PostMapping("/course-package")
    public AjaxResult insert(@Valid @RequestBody CoursePackageDto dto) {
        log.info("Rest request to insert coursePackage:{}", dto);
        int id = coursePackageService.insert(dto);
        CoursePackage result = coursePackageService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 更新课程包
     *
     * @param dto
     * @return
     */
    @PutMapping("/course-package")
    public AjaxResult update(@Valid @RequestBody CoursePackageDto dto) {
        log.info("Rest request to update coursePackage:{}", dto);
        coursePackageService.update(dto);
        CoursePackage result = coursePackageService.selectById(dto.getId());
        return AjaxResult.success(result);
    }

    /**
     * 批量更新课程包状态
     *
     * @param dto
     * @return
     */
    @PutMapping("/course-package-batch")
    public AjaxResult update(@Valid @RequestBody BatchDto dto) {
        log.info("Rest request to batch-update course-package:{}", dto);
        coursePackageService.batchUpdateStatus(dto);
        return AjaxResult.success();
    }

    /**
     * 批量删除课程包
     *
     * @param dto
     * @return
     */
    @DeleteMapping("/course-package-batch")
    public AjaxResult deleteById(@RequestBody BatchDto dto) {
        log.info("Rest request to batch-delete course-package by id:{}", dto);
        int row = coursePackageService.batchDelete(dto);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 获取课程包详情
     *
     * @param id
     * @return
     */
    @GetMapping("/course-package/{id}")
    public AjaxResult selectById(@PathVariable Integer id) {
        log.info("Rest request to find coursePackage by id:{}", id);
        SysUser user = null;
        String token = UserSessionUtil.resolveToken();
        if (StringUtils.isNotBlank(token)) {
            user = userUtils.getCurrentUser();
        }
        long startTime = System.currentTimeMillis();   //获取开始时间
        CoursePackage result = coursePackageService.selectById(id);
        long endTime = System.currentTimeMillis(); //获取结束时间
        log.info("A id:{} ms", endTime - startTime);
        if (user != null) {
            //判断是否已经购买该课程包，手机端使用
            if (user.getStudent() != null) {
                long startTimeB = System.currentTimeMillis();   //获取开始时间
                int count = studentCoursePackageMapper.selectByStudentIdAndCoursePackageId(id, user.getStudent().getId());
                long endTimeB = System.currentTimeMillis(); //获取结束时间
                log.info("B id:{} ms", endTimeB - startTimeB);
                if (count > 0) {
                    result.setIsBuy(true);
                }
            }
            if (user.getTrainingOrganization() != null) {
                long startTimeC = System.currentTimeMillis();   //获取开始时间
                List<TrainingOrganizationStock> trainingOrganizationStockList = trainingOrganizationStockMapper.selectByTrainingOrganizationIdProductIdAndTypeList(user.getTrainingOrganization().getId(), id, OrderTypeEnum.COURSE_PACKAGE.getValue());
                long endTimeC = System.currentTimeMillis(); //获取结束时间
                log.info("C id:{} ms", endTimeC - startTimeC);
                long startTimeD = System.currentTimeMillis(); //获取结束时间
                if (trainingOrganizationStockList != null && trainingOrganizationStockList.size() > 0) {
                    for (TrainingOrganizationStock item : trainingOrganizationStockList) {
                        if (trainingOrganizationStockService.whetherOverdue(item.getOrderId()) == true) {
                            result.setIsBuy(true);
                            break;
                        }
                    }
                }
                long endTimeD = System.currentTimeMillis(); //获取结束时间
                log.info("D id:{} ms", endTimeD - startTimeD);
            }
        }
        return AjaxResult.success(result);
    }

    /**
     * 个人获取课程包详情
     *
     * @param id
     * @return
     */
    @GetMapping("/course-package/{id}/{userId}")
    public AjaxResult selectByUserId(@PathVariable Integer id, @PathVariable String userId) throws IOException, NoSuchAlgorithmException {
        log.info("Rest request to find coursePackage by id:{}", id);
        CoursePackage result = coursePackageService.selectByUserId(id, userId);
        result.setIsBuy(true);

        return AjaxResult.success(result);
    }

    /**
     * 删除课程包
     *
     * @param id
     * @return
     */
    @DeleteMapping("/course-package/{id}")
    public AjaxResult deleteById(@PathVariable Integer id) {
        log.info("Rest request to delete coursePackage by id:{}", id);
        int row = coursePackageService.delete(id);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 分页查询课程包
     *
     * @param courseName 课程包名
     * @param categoryId 分类id
     * @param status     课程包状态
     * @param sortStatus 排序状态（1、最新、2、最热、3、免费）
     * @param ascColumn  升序排序字段
     * @param descColumn 降序怕徐字段
     * @param pageable   分页信息
     * @return
     */
    @GetMapping("/course-package")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String courseName, @RequestParam(required = false) Integer plateId, @RequestParam(required = false) Boolean recommend, @RequestParam(required = false) Integer categoryId, @RequestParam(required = false) Integer status, @RequestParam(required = false, defaultValue = "") String ascColumn, @RequestParam(required = false, defaultValue = "") String descColumn, @RequestParam(required = false) Integer sortStatus, @RequestParam(required = false) Integer rank, Pageable pageable) {
        String orderStr = OrderUtil.genOrderStr(ascColumn, descColumn);
        log.info("Rest request to find coursePackage by params courseName:{},categoryId:{}:status:{},orderStr:{}", courseName, categoryId, status, orderStr);
        List<Integer> categoryIds = coursePackageService.selectDeepCategoryIds(categoryId);
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<CoursePackage> coursePackages = coursePackageService.selectDeepByParams(courseName, plateId, recommend, categoryIds, status, orderStr, rank, sortStatus);
        PageInfo<CoursePackage> result = new PageInfo<>(coursePackages);
        return AjaxResult.success(result);
    }

    /**
     * 查询课程包列表
     *
     * @param courseName 课程包名
     * @param categoryId 分类id
     * @param status     课程包状态
     * @param ascColumn  升序排序字段
     * @param descColumn 降序怕徐字段
     * @return
     */
    @GetMapping("/course-package-list")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String courseName, @RequestParam(required = false) Integer plateId, @RequestParam(required = false) Boolean recommend, @RequestParam(required = false) Integer categoryId, @RequestParam(required = false) Integer status, @RequestParam(required = false, defaultValue = "") String ascColumn, @RequestParam(required = false, defaultValue = "") String descColumn, @RequestParam(required = false) Integer rank, @RequestParam(required = false) Integer sortStatus) {
        String orderStr = OrderUtil.genOrderStr(ascColumn, descColumn);
        log.info("Rest request to find coursePackage by params courseName:{},categoryId:{}:status:{},orderStr:{}", courseName, categoryId, status, orderStr);
        List<Integer> categoryIds = coursePackageService.selectDeepCategoryIds(categoryId);
        List<CoursePackage> result = coursePackageService.selectDeepByParams(courseName, plateId, recommend, categoryIds, status, orderStr, rank, sortStatus);
        return AjaxResult.success(result);
    }

    /**
     * 查询内容分类返回树形结构
     *
     * @param pid 父级分类id
     * @return
     */
    @GetMapping("/course-package-son/{pid}")
    public AjaxResult selectByPid(@PathVariable Integer pid) {
        log.info("Rest request to find ContentCategory by pid:{}", pid);
        CoursePackageData result = coursePackageService.selectSon(pid);
        return AjaxResult.success(result);
    }

}
